﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;



using WAF.DAO;
using WAF.EntityFramework;

namespace TradeClient.Views
{
    public partial class BasicDataForm : Form
    {
        private string  entityName = "";        //实体类名称
        private Type    entityType = null;      //实体类类型
        private DataRow newRow = null;          //包含新增行数据
        private bool cellValueChanged = false;  //单元格数据是否被修改过

        public BasicDataForm()
        {
            InitializeComponent();
        }

        //实体类清单
        private void BasicDataForm_Load(object sender, EventArgs e)
        {
            //设置按钮文本和图像
            SetButtonIconAndText();

            treeViewMenu.Nodes.Add("CtpBroker", "经纪商");
            treeViewMenu.Nodes.Add("CtpAccount", "账号");
            //treeViewMenu.Nodes.Add("FrontAddress", "前置机地址");
            //treeViewMenu.Nodes.Add("FrontAddressGroup", "前置机地区");
            //treeViewMenu.Nodes.Add("FrontAddressType", "前置机类型");
            //treeViewMenu.Nodes.Add("Instrument", "期货合约");
        }

        //切换表之前检查是否有未保存的新增记录
        private void treeViewMenu_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (newRow != null)
            {
                e.Cancel = true;
                foreach (DataGridViewRow row in dataGridViewItemList.SelectedRows) row.Selected = false;
                dataGridViewItemList.Rows[dataGridViewItemList.Rows.Count - 1].Selected = true;
                MessageBox.Show("还有未保存的记录！");
            }
        }

        //显示相应实体类列表
        private void treeViewMenu_AfterSelect(object sender, TreeViewEventArgs e)
        {
            toolStripTextBoxSearch.Text = "";
            dataGridViewItemList.DataSource = null;
            dataGridViewItemList.Columns.Clear();
            dataGridViewItemList.AutoGenerateColumns = false;
            groupBoxItemList.Text = treeViewMenu.SelectedNode.Text;

            entityName = treeViewMenu.SelectedNode.Name;
            entityType = Type.GetType("TradeClient.Logic.Entity." + entityName);

            foreach (PropertyInfo pInfo in EntitySession.GetPropertiesOrder(entityType))
            {
                EntityFieldAttribute fAttribute = pInfo.GetCustomAttributes(typeof(EntityFieldAttribute), false)[0] as EntityFieldAttribute;

                if (!fAttribute.IsForeignKey)
                {
                    DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();

                    col.Name = pInfo.Name;
                    col.DataPropertyName = pInfo.Name;
                    col.HeaderText = fAttribute.Label;

                    col.MinimumWidth = 100;
                    col.Visible = (pInfo.Name == "Id" ? false : true);
                    
                    dataGridViewItemList.Columns.Add(col);
                }
                else
                {
                    DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();

                    Type refEntityType = Type.GetType("TradeClient.Logic.Entity." + fAttribute.RefTable);
                    int totel = 0;
                    DataTable tb = EntityAction.GetGridData(refEntityType, "", out totel);

                    col.DataSource = tb;
                    col.Name = pInfo.Name;
                    col.HeaderText = fAttribute.Label;
                    col.DataPropertyName = pInfo.Name;
                    col.ValueMember = "Id";
                    col.DisplayMember = fAttribute.RefLableField;

                    col.MinimumWidth = 100;
                    col.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;

                    dataGridViewItemList.Columns.Add(col);
                }
            }

            BindDataGridView();
        }

        //模糊查询
        private void toolStripButtonSearch_Click(object sender, EventArgs e)
        {
            BindDataGridView();
        }

        //添加
        private void toolStripButtonAdd_Click(object sender, EventArgs e)
        {
            //新增行，并将新增按钮改成保存按钮，删除按钮改成取消保存按钮
            if (newRow == null)
            {
                DataTable tb = (DataTable)dataGridViewItemList.DataSource;

                newRow = tb.NewRow();
                tb.Rows.Add(newRow);

                SetButtonIconAndText();
            }
            //保存新增数据
            else
            {
                bool validate = true;
                Entity entity = (Entity)Activator.CreateInstance(entityType);

                //检查所有实体类字段的合法性并赋值
                foreach (PropertyInfo pInfo in EntitySession.GetPropertiesOrder(entityType))
                {
                    if (pInfo.Name == "Id") continue;

                    //检查字段合法性
                    object colValue = newRow[pInfo.Name];
                    string errorMsg = "";// EntitySession.ValidateField(pInfo, colValue);
                    dataGridViewItemList.Rows[dataGridViewItemList.Rows.Count-1].Cells[pInfo.Name].ErrorText = errorMsg;

                    //如果验证失败则不给实体类字段赋值
                    if (errorMsg != "") 
                        validate = false;
                    else 
                        pInfo.SetValue(entity, newRow[pInfo.Name], null);
                }

                //当有字段验证失败时返回
                if (!validate) return;

                //保存新增数据
                //entity.Insert();
                EntityAction.Insert(entity);
                BindDataGridView();

                //清除新行，恢复按钮样式
                newRow = null;
                SetButtonIconAndText();
                MessageBox.Show("保存成功！");
            }
        }

        //修改（需双击）
        private void dataGridViewItemList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            dataGridViewItemList.BeginEdit(true);
        }

        //删除
        private void toolStripButtonDelete_Click(object sender, EventArgs e)
        {
            //删除数据
            if (newRow == null)
            {
                if (dataGridViewItemList.SelectedRows.Count == 0)
                {
                    MessageBox.Show("请选择一条记录！");
                    return;
                }

                if (MessageBox.Show("确定要删除这些记录吗？", "删除", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    foreach (DataGridViewRow row in dataGridViewItemList.SelectedRows)
                    {
                        long selectID = int.Parse(row.Cells[0].Value.ToString());
                        EntityAction.Delete(entityType, selectID);
                    }

                    BindDataGridView();
                }
            }
            //取消保存新增数据
            else
            {
                DataTable tb = (DataTable)dataGridViewItemList.DataSource;
                tb.Rows.Remove(newRow);

                //清除新行，恢复按钮样式
                newRow = null;
                SetButtonIconAndText();
            }
        }

        //单元格的值改变时设置标志
        private void dataGridViewItemList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            cellValueChanged = true;
        }

        //离开单元格时在数据库中更新该单元格数据
        private void dataGridViewItemList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //如果当前单元格的值未改变过则不做操作
            if (!cellValueChanged) { cellValueChanged = false; return; }

            //当前单元格信息
            DataGridViewCell currentCell = dataGridViewItemList.Rows[e.RowIndex].Cells[e.ColumnIndex];
            string rowid = dataGridViewItemList.Rows[e.RowIndex].Cells["Id"].Value.ToString();
            string colName  = currentCell.OwningColumn.Name;
            object colValue = currentCell.Value.ToString().Trim();

            //获取该字段信息
            PropertyInfo pInfo = entityType.GetProperty(colName);
            EntityFieldAttribute fAttribute = pInfo.GetCustomAttributes(typeof(EntityFieldAttribute), false)[0] as EntityFieldAttribute;

            //验证字段值的合法性
            currentCell.ErrorText = "";// EntityBase.ValidateField(pInfo, colValue);

            //数据通过验证后更新数据，如果是新增行的数据则不更新
            if (rowid != "" && currentCell.ErrorText == "")
            {
                //构建SQL语句
                StringBuilder sb = new StringBuilder();
                sb.Append("update ").Append(entityName).Append(" set ").Append(colName).Append("=@value where Id=").Append(rowid);

                //添加SQL参数
                DbParameters parms = new DbParameters();
                parms.Add("value", colValue, fAttribute.FieldDbType);

                //保存数据
                DbAccess.ExeNonQuery(sb.ToString(), parms);
                
                //重置更改标志
                cellValueChanged = false;
            }
        }

        //邦定DataGrid
        private int BindDataGridView()
        {
            int total = 0;

            dataGridViewItemList.DataSource = EntityAction.GetGridData(Type.GetType("TradeClient.Logic.Entity." + entityType.Name), toolStripTextBoxSearch.Text.Trim(), out total);

            return total;
        }

        //设置按钮图标和文本
        private void SetButtonIconAndText()
        {
            if (newRow == null)
            {
                toolStripButtonAdd.Text = "新增";
                toolStripButtonAdd.Image = Bitmap.FromFile("./Images/add_small.ico");
                toolStripButtonDelete.Text = "删除";
                toolStripButtonDelete.Image = Bitmap.FromFile("./Images/remove_small.ico");
            }
            else
            {
                toolStripButtonAdd.Text = "保存";
                toolStripButtonAdd.Image = Bitmap.FromFile("./Images/save.ico");
                toolStripButtonDelete.Text = "取消";
                toolStripButtonDelete.Image = Bitmap.FromFile("./Images/gem_remove.png");
            }
        }

        private void dataGridViewItemList_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("输入的数字格式不正确！");
        }
    }
}
